// -----------------------------------------------------------------------
//  <copyright file="DeleteDictionaryItemCommand.cs" company="LiuliuSoft">
//      Copyright (c) 2025 66SOFT. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-10-17 01:10</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Authorization;
using DaprPlus.Domain;
using DaprPlus.DataDicts.Domain.Entities;
using DaprPlus.DataDicts.Domain.Specs;
using DaprPlus.Domain.Entity;
using DaprPlus.MediatR;


namespace DaprPlus.DataDicts.Application.Commands;

[AuthConfig(typeof(DictionaryItem), ResourceAccessType.RoleLimit, "Delete")]
public class DeleteDictionaryItemCommand(long typeId, long[] itemIds) : IRequest<ApiResult>, ICommand
{
    public long TypeId { get; set; } = typeId;
    public long[] ItemIds { get; set; } = itemIds;
}

public class DeleteDictionaryItemCommandHandler(IServiceProvider provider)
    : IRequestHandler<DeleteDictionaryItemCommand, ApiResult>
{
    public async Task<ApiResult> Handle(DeleteDictionaryItemCommand request, CancellationToken cancellationToken)
    {
        var logger = provider.GetLogger<DeleteDictionaryItemCommandHandler>();
        var typeRepository = provider.GetRepository<DictionaryType>();

        // 根据指定的TypeId获取字典类型
        var spec = new DictionaryTypeByIdSpec(request.TypeId)
            .And(new DictionaryTypeWithItemsSpec());
        var dictionaryType = await typeRepository.GetAsync(spec, cancellationToken);

        if (dictionaryType == null)
        {
            logger.LogWarning("删除字典项时编号为 {TypeId} 的字典类型不存在", request.TypeId);
            return new ApiResult(ApiResultType.Error, $"编号为 {request.TypeId} 的字典类型不存在");
        }

        // 直接删除传入的字典项ID
        var result = dictionaryType.RemoveItem(request.ItemIds);
        if (!result.IsSuccess())
        {
            logger.LogWarning("删除字典项失败：{Message}", result.Message);
            return result;
        }

        await typeRepository.UpdateAsync(dictionaryType, cancellationToken);

        logger.LogInformation("字典类型 {TypeName} 下编号为【{Ids}】的字典项信息删除成功，数量：{Count}",
            dictionaryType.Name, request.ItemIds, request.ItemIds.Length);

        return new ApiResult(ApiResultType.Success,
            $"字典类型 {dictionaryType.Name} 下的 {request.ItemIds.Length} 个字典项删除成功");
    }
}
